package com.heart.house.user.service;

import com.google.common.cache.*;
import com.heart.house.user.mapper.UserMapper;
import com.heart.house.user.model.User;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author Luo Zhen
 * @create 2019-06-19 14:23
 */
@Service
public class MailService {

    private final Cache<String, String> registerCache = CacheBuilder.newBuilder()
            .maximumSize(100).expireAfterAccess(15, TimeUnit.MINUTES)
            .removalListener(new RemovalListener<String, String>() {
                @Override
                public void onRemoval(RemovalNotification<String, String> notification) {
                    if (notification.getCause() == RemovalCause.EXPIRED) {
                        userMapper.delete(notification.getValue());
                    }
                }
            }).build();

    @Autowired
    private UserMapper userMapper;

    @Value("${domain.name}")
    private String domainName;

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮件
     *
     * @param title
     * @param url
     * @param email
     */
    public void sendMail(String title, String url, String email) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setSubject(title);
        message.setTo(email);
        message.setText(url);
        mailSender.send(message);
    }

    /**
     * 缓存key - mail的关系
     * 借助Springmail发送邮件
     * 借助异步框架进行异步操作
     *
     * @param email
     */
    @Async
    public void registerNotify(String email) {
        String randomKey = RandomStringUtils.randomAlphabetic(10);
        registerCache.put(randomKey, email);
        String url = "http://" + domainName + "/accounts/verify?key=" + randomKey;
        sendMail("房产激活链接", url, email);
    }

    public boolean enable(String key) {
        String email = registerCache.getIfPresent(key);
        if (StringUtils.isBlank(email)) {
            return false;
        }
        User updateUser = new User();
        updateUser.setEmail(email);
        updateUser.setEnable(1);

        userMapper.update(updateUser);
        registerCache.invalidate(key);
        return true;
    }
}
